package com.glodon.async.threadpool;

import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 管理线程池：负责创建、修改、状态监控
 * @Author: lilin
 * @Date: 2022/8/13
 */
public class DynamicThreadPoolManager {

    /**
     * 存储线程池对象，key：线程名  value:线程池对象
     */
    private static HashMap<String, DynamicThreadPoolExecutor> threadPoolExecutorMap = new HashMap<>();

    /**
     * 创建线程池
     * @param poolName 线程池名称
     * @param corePoolSize 核心线程数
     * @param maxPoolSize 最大线程数
     * @param keepAliveTime 存活时间
     * @param timeUnit 单位
     * @param workQueue 等待队列
     */
    public static DynamicThreadPoolExecutor createDynamicThreadPoolExecutor(String poolName, Integer corePoolSize, Integer maxPoolSize, Long keepAliveTime, TimeUnit timeUnit, BlockingQueue<Runnable> workQueue){
        DynamicThreadPoolExecutor dynamicThreadPoolExecutor = new DynamicThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, timeUnit, workQueue);
        threadPoolExecutorMap.put(poolName, dynamicThreadPoolExecutor);
        return dynamicThreadPoolExecutor;
    }

    public static void refreshThreadPoolExecutor(String poolName, Integer corePoolSize, Integer maxPoolSize, Long keepAliveTime, TimeUnit timeUnit, Integer size){
        DynamicThreadPoolExecutor dynamicThreadPoolExecutor = threadPoolExecutorMap.get(poolName);
        dynamicThreadPoolExecutor.setCorePoolSize(corePoolSize);
        dynamicThreadPoolExecutor.setMaximumPoolSize(maxPoolSize);
        dynamicThreadPoolExecutor.setKeepAliveTime(keepAliveTime, timeUnit);
        BlockingQueue<Runnable> queue = dynamicThreadPoolExecutor.getQueue();
        if (queue instanceof ResizableCapacityLindedBlockingQueue) {
            ((ResizableCapacityLindedBlockingQueue<Runnable>) queue).setCapacity(size);
        }
    }

    /**
     * 打印线程池配置信息
     */
    public static void printThreadPoolExecutor(String poolName){
        DynamicThreadPoolExecutor poolExecutor = threadPoolExecutorMap.get(poolName);
        System.out.println("【线程池配置信息】线程名称：" + poolName +
                "    corePoolSize：" + poolExecutor.getCorePoolSize() +
                "    maxiPoolSize：" + poolExecutor.getMaximumPoolSize() +
                "    Queue：" + poolExecutor.getQueue().remainingCapacity());
    }

    /**
     * 打印任务状态
     */
    public static void printTaskStatus(String poolName){
        DynamicThreadPoolExecutor poolExecutor = threadPoolExecutorMap.get(poolName);
        System.out.println("【任务状态打印】线程名称：" + poolName +
                "    活动线程数：" + poolExecutor.getActiveCount() +
                "    累计提交任务总数：" + poolExecutor.getCompletedTaskCount() +
                "    出现过最大线程个数：" + poolExecutor.getLargestPoolSize() +
                "    已缓存任务数：" +  poolExecutor.getQueue().size());
        poolExecutor.print();
    }

}
